﻿
////选择商品
//function SelectProducts(isSingle) {
//    var diag = new Dialog();
//    diag.Title = "选择商品";
//    diag.Width = 800;
//    diag.Height = 510;
//    diag.URL = "/HomePage/SelectProducts?isSingle=" + isSingle;
//    diag.OKEvent = function () {
//        diag.innerFrame.contentWindow.document.getElementById('hidBtn').click();
//        var tempVar = diag.innerFrame.contentWindow.document.getElementById('hidId').value;
//        var tempJson = eval('(' + tempVar + ')');
//        SelectProductOK(tempJson);
//        diag.close();
//    };
//    diag.show();
//}

////选择商品修改选择的行
//function SelectProduct(isSingle, obj) {
//    var diag = new Dialog();
//    diag.Title = "选择商品";
//    diag.Width = 800;
//    diag.Height = 520;
//    diag.URL = "/HomePage/SelectProducts?isSingle=" + isSingle;
//    diag.OKEvent = function () {
//        diag.innerFrame.contentWindow.document.getElementById('hidBtn').click();
//        var tempVar = diag.innerFrame.contentWindow.document.getElementById('hidId').value;
//        var tempJson = eval('(' + tempVar + ')');
//        SelectProductOK(tempJson, obj);
//        diag.close();
//    };
//    diag.show();
//}

//选择商品修改选择的行
//busiAction:Sale：销售单；Buy：进货单
function SelectProductByBusi(obj, busiAction) {
    parent.$("#divLoading").show();
    parent.$('#openFrameDiv').dialog({
        title: '选择商品',
        width: 900,
        height: 580,
        closed: false,
        cache: false,
        modal: true,
        maximizable: true,
        resizable: true,
        buttons: [{
            text: '确定',
            cls: 'greenbutton',
            handler: function () {
                var isAdd = parent.$('#openIframe')[0].contentWindow.$("#hidShareAdd").val();
                if (isAdd == "shareAdd") {
                    parent.$('#openIframe')[0].contentWindow.$("form:eq(0)").submit();
                    //parent.$('#openIframe')[0].contentWindow.window.location = "/HomePage/SelectProducts?isSingle=" + isSingle + "&BusiAction=" + busiAction;
                }
                else {
                    var tempJson =  parent.$("#tabs .panel:visible iframe")[0].contentWindow.sel_products;
                   
                    parent.$("#tabs .panel:visible iframe")[0].contentWindow.SelectProductOK(tempJson, obj);
                    parent.$('#openFrameDiv').dialog('close');
                }
            }
        }, {
            text: '取消',
            handler: function () {               
                 parent.$('#openFrameDiv').dialog('close')
            }
        }]
    });
    parent.$('#openIframe')[0].src = "/ProductInfo/List?busiaction=" + busiAction;
    parent.$('#openFrameDiv').dialog('open');
}




//选择商品修改选择的行
//busiAction:Sale：销售单；Buy：进货单
function SelectWareProductByBusi(obj, busiAction) {
    parent.$("#divLoading").show();
    parent.$('#openFrameDiv').dialog({
        title: '选择商品',
        width: 1000,
        height: 600,
        closed: false,
        cache: false,
        modal: true,
        maximizable: true,
        resizable: true,
        buttons: [{
            text: '确定',
            iconcls: 'l-btn-left2',
            handler: function () {                   
                    parent.$("#tabs .panel:visible iframe")[0].contentWindow.SelectProductOK(tempJson, obj);                 
                    parent.$('#openFrameDiv').dialog('close');
                
            }
        }, {
            text: '取消',
            handler: function () {
                var isAdd = parent.$('#openIframe')[0].contentWindow.$("#hidShareAdd").val();
                if (isAdd == "shareAdd") {
                    parent.$('#openIframe')[0].contentWindow.window.location = "/HomePage/SelectProducts?WarehouseId=" + warehouseId + "&BusiAction=" + busiAction;
                }
                else {
                    parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + busiAction + "ChooseGoods").val('');
                    parent.$('#openFrameDiv').dialog('close');
                }
            }
        }]
    });
    parent.$('#openIframe')[0].src = "/ProductInfo/List?BusiAction=" + busiAction;
    parent.$('#openFrameDiv').dialog('open');
}

//选择序列号
//busiAction: Sale：销售单；Buy：进货单
function SelectSerialNo(tempJson, warehouseId, busiAction) {
    //商品编号（逗号隔开）
    var strProductIds = '';
    //行号guid
    var strRowIds = '';
    //只要选择的商品中有序列号管理启用必填的就弹窗
    for (var i = 0; i < tempJson.length; i++) {
        if (tempJson[i]["SNManage"] == "1") {
            tempJson[i]["RowId"] = guidGenerator();
            strProductIds = strProductIds + tempJson[i]["ID"] + ",";
            strRowIds = strRowIds + tempJson[i]["RowId"] + ',';
        }
        if (tempJson[i]["SNManage"] == "2") {
            tempJson[i]["RowId"] = guidGenerator();
        }
    }
    if (strProductIds != '') {
        //进货直接退货同销售
        if (busiAction == "Sale" || busiAction == "BuyReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 900,
                height: 530,
                closed: false,
                cache: false,
                modal: true,
                maximizable: false,
                resizable: true,
                buttons: null
            });
            parent.$('#openSNManageIframe')[0].src = "/HomePage/SelectSN?ProductIds=" + strProductIds + "&WarehouseId=" + warehouseId + "&RowIds=" + strRowIds;
            parent.$('#SNManageDIV').dialog('open');
        }
        //销售直接退货同进货
        if (busiAction == "Buy" || busiAction == "SaleReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 600,
                height: 580,
                closed: false,
                cache: false,
                modal: true,
                maximizable: false,
                resizable: true,
                buttons: null
            });
            // 商品名称组   商品ID组  仓库名称  业务类型（用来标识第一参数是仓库还是商品  0：仓库 1：商品）   仓库ID   商品单位

            parent.$('#openSNManageIframe')[0].src = "/HomePage/BillSNManage?ProductIds=" + strProductIds
                + "&WarehouseId=" + warehouseId
                + "&RowIds=" + strRowIds;

            parent.$('#SNManageDIV').dialog('open');
        }
    }
}


//单行商品选择序列号
//busiAction: Sale：销售单；Buy：进货单
function SingleSelectSerialNo(productId, RowId, warehouseId, busiAction) {
    if (productId != '' && RowId != '') {
        //进货直接退货同销售
        if (busiAction == "Sale" || busiAction == "BuyReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 900,
                height: 530,
                closed: false,
                cache: false,
                modal: true,
                maximizable: false,
                resizable: true,
                buttons: null
            });
            parent.$('#openSNManageIframe')[0].src = "/HomePage/SelectSN?ProductIds=" + productId + "&WarehouseId=" + warehouseId + "&RowIds=" + RowId;
            parent.$('#SNManageDIV').dialog('open');
        }
        //销售直接退货同进货
        if (busiAction == "Buy" || busiAction == "SaleReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 600,
                height: 580,
                closed: false,
                cache: false,
                modal: true,
                maximizable: false,
                resizable: true,
                buttons: null
            });
            // 商品名称组   商品ID组  仓库名称  业务类型（用来标识第一参数是仓库还是商品  0：仓库 1：商品）   仓库ID   商品单位

            parent.$('#openSNManageIframe')[0].src = "/HomePage/BillSNManage?ProductIds=" + productId
                + "&WarehouseId=" + warehouseId
                + "&RowIds=" + RowId;

            parent.$('#SNManageDIV').dialog('open');
        }
    }
}
//选择商品弹出框 单行商品选择序列号
//busiAction: Sale：销售单；Buy：进货单
function SelectProductSingleSelectSerialNo(productId, RowId, warehouseId, busiAction) {
    if (productId != '' && RowId != '') {
        //进货直接退货同销售
        if (busiAction == "Sale" || busiAction == "BuyReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 900,
                height: 530,
                closed: false,
                cache: false,
                modal: true,
                maximizable: false,
                resizable: true,
                buttons: null
            });
            parent.$('#openSNManageIframe')[0].src = "/HomePage/SelectProductSN?ProductIds=" + productId + "&WarehouseId=" + warehouseId + "&RowIds=" + RowId;
            parent.$('#SNManageDIV').dialog('open');
        }
        //销售直接退货同进货
        if (busiAction == "Buy" || busiAction == "SaleReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 600,
                height: 580,
                closed: false,
                cache: false,
                modal: true,
                maximizable: false,
                resizable: true,
                buttons: null
            });
            // 商品名称组   商品ID组  仓库名称  业务类型（用来标识第一参数是仓库还是商品  0：仓库 1：商品）   仓库ID   商品单位

            parent.$('#openSNManageIframe')[0].src = "/HomePage/SelectProductSNManage?ProductIds=" + productId
                + "&WarehouseId=" + warehouseId
                + "&RowIds=" + RowId;

            parent.$('#SNManageDIV').dialog('open');
        }
    }
}
//单行商品选择序列号
//busiAction: Sale：销售单；Buy：进货单
//busiType:1:归还 2：退货
function SingleSelectSerialNoByAllow(productId, RowId, warehouseId, busiAction, allowCount, busiType) {
    if (productId != '' && RowId != '') {
        //进货直接退货同销售
        if (busiAction == "Sale" || busiAction == "BuyReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 900,
                height: 530,
                closed: false,
                cache: false,
                modal: true,
                maximizable: false,
                resizable: true,
                buttons: null
            });
            parent.$('#openSNManageIframe')[0].src = "/HomePage/SelectSN?ProductIds=" + productId + "&WarehouseId=" + warehouseId + "&RowIds=" + RowId + "&allowCount=" + allowCount + "&busiType=" + busiType;
            parent.$('#SNManageDIV').dialog('open');
        }
        //销售直接退货同进货
        if (busiAction == "Buy" || busiAction == "SaleReturn") {
            parent.$('#SNManageDIV').dialog({
                title: '序列号管理',
                width: 600,
                height: 580,
                closed: false,
                cache: false,
                modal: true,
                maximizable: false,
                resizable: true,
                buttons: null
            });
            // 商品名称组   商品ID组  仓库名称  业务类型（用来标识第一参数是仓库还是商品  0：仓库 1：商品）   仓库ID   商品单位

            parent.$('#openSNManageIframe')[0].src = "/HomePage/BillSNManage?ProductIds=" + productId
                + "&WarehouseId=" + warehouseId
                + "&RowIds=" + RowId
                + "&allowCount=" + allowCount
                + "&busiType=" + busiType;

            parent.$('#SNManageDIV').dialog('open');
        }
    }
}

//guid生成
function guidGenerator() {
    var S4 = function () {
        return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
    };
    return (S4() + S4() + "-" + S4() + "-" + S4() + "-" + S4() + "-" + S4() + S4() + S4());
}

//选择商品修改选择的行
//busiAction:盘点专用
function SelectWareProductByBusiStore(obj, busiAction, warehouseId) {
    parent.$("#divLoading").show();
    parent.$('#openFrameDiv').dialog({
        title: '选择商品',
        width: 900,
        height: 580,
        closed: false,
        cache: false,
        modal: true,
        maximizable: false,
        resizable: true,
        buttons: [{
            text: '确定',
            handler: function () {
                var isAdd = parent.$('#openIframe')[0].contentWindow.$("#hidShareAdd").val();
                if (isAdd == "shareAdd") {
                    parent.$('#openIframe')[0].contentWindow.$("form:eq(0)").submit();
                }
                else {
                    var tempJson = parent.$('#openIframe')[0].contentWindow.initData();
                    parent.$("#tabs .panel:visible iframe")[0].contentWindow.SelectProductOK(tempJson, obj);
                    parent.$('#openFrameDiv').dialog('close');
                }
            }
        }, {
            text: '取消',
            handler: function () {
                var isAdd = parent.$('#openIframe')[0].contentWindow.$("#hidShareAdd").val();
                if (isAdd == "shareAdd") {
                    parent.$('#openIframe')[0].contentWindow.window.location = "/HomePage/SelectProducts?WarehouseId=" + warehouseId + "&BusiAction=" + busiAction;
                }
                else {
                    parent.$('#openFrameDiv').dialog('close')
                }
            }
        }]
    });
    parent.$('#openIframe')[0].src = "/HomePage/SelectProducts?WarehouseId=" + warehouseId + "&BusiAction=" + busiAction;
    parent.$('#openFrameDiv').dialog('open');
}





//盘点序列号 
//单据id，单据明细id，商品id，仓库id，允许序列号数（选填),盘点类型（1，第一次盘点；2，后期盘点),snMange(1.必填；2.选填）
function PDSerialNo(takBillId, takId, productId, warehouseId, allowCount, type) {
    if (productId != '') {
        parent.$('#SNManageDIV').dialog({
            title: '盘点序列号',
            width: 900,
            height: 560,
            closed: false,
            cache: false,
            modal: true,
            maximizable: false,
            resizable: true,
            buttons: null
        });
        parent.$('#openSNManageIframe')[0].src = "/HomePage/PDSN?ProductIds=" + productId + "&WarehouseId=" + warehouseId
        + "&TakBillId=" + takBillId + "&TakId=" + takId + "&allowCount=" + allowCount + "&storeType=" + type;//+"&snManage="+snManage;
        parent.$('#SNManageDIV').dialog('open');
    }
}


//核销
function HXRC(obj, busiId, busiType, hxType) {
    var msg = "";
    if (hxType == 1) {
        msg = "确定要核销这张单据吗？";
    }
    if (hxType == 2) {
        msg = "确定要撤销已核销的这张单据吗？";
    }
    //parent.$.messager.confirm('系统提示', msg, function (r) {
    //if (r) {
    $.ajax({
        dataType: "json",
        data: {
            busiId: busiId,
            busiType: busiType,
            hxType: hxType
        },
        url: "/HomePage/HXRC/",
        cache: false,
        type: "post",
        async: false,
        success: function (data) {
            var resultArr = data.split("|");
            if (resultArr.length == 3) {
                if (hxType == 1) {
                    $(obj).parent().parent().find('.hxqk').hide();
                    $(obj).parent().parent().find('.hhxqk').show();
                    $(obj).parent().parent().find('.hxTime').html(resultArr[1]);
                    $(obj).parent().parent().find('.hxUser').html(resultArr[2]);
                }
                else {
                    $(obj).parent().parent().parent().parent().find('.hxqk').show();
                    $(obj).parent().parent().parent().parent().find('.hhxqk').hide();
                }
            }
            else {
                Dialog.alert(data);
            }
        },
        error: function () {
            Dialog.alert("核销失败");
        }
    });
    //}
    //});
}

//获取当前商品库存数
function GetProductStockCount(productId, warehouseId) {
    var count = 0;
    $.ajax({
        dataType: "json",
        data: { productId: productId, warehouseId: warehouseId },
        cache: false,
        async: false,
        url: "/HomePage/GetProductStockCount/?" + Math.random(),
        type: "post",
        success: function (data) {
            count = data.Data;
        },
        error: function () {
            count = 0;
        }
    });
    return count;
}
Array.prototype.remove = function (dx) {
    if (isNaN(dx) || dx > this.length) { return false; }
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[dx]) {
            this[n++] = this[i]
        }
    }
    this.length -= 1
}
//单个checkbox点击
function ChooseGoods(product) {		
	var BusiAction = request("BusiAction");
	if (!BusiAction) return;	
	
	if (product.sel){				
		parent.$("#tabs .panel:visible iframe")[0].contentWindow.selectProduct(product);
	}
	else{		
		parent.$("#tabs .panel:visible iframe")[0].contentWindow.unSelectProduct(product);
	}   
    SumGoodsNum();
}
//全选
function chooseAll(productSn) {
    var hidIsOpenIO = $("#hidIsOpenIO").val();
    var hidIsRealTimeIO = parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#IsLogisOut").val();
    //商品编号（逗号隔开）
    var strProductIds = '';
    //行号guid
    var strRowIds = '';
    var warehouseId = request("WarehouseId");
    var BusiAction = request("BusiAction");
    var flag = 0;//标识是选中还是取消选中
    $("input[selable='1']").each(function () {
        if ($(this).parent().find("input[name='hidSNManage']").val() == 1 && $(this).attr("checked") == "checked" && productSn == "1" && ((hidIsOpenIO == "1" && hidIsRealTimeIO == "1") || hidIsOpenIO == "0")) {
            flag = 1;
            $(this).removeAttr("checked");
            strProductIds = strProductIds + this.value + ",";
            strRowIds = strRowIds + $(this).parent().find("input[name='hidRowId']").val() + ',';
        }
        else {
            var count = $(this).parent().parent().children('td').eq(10).find("input[name='TxgoodsNum']").val();
            var serialId = $(this).parent().find("input[name='hidSerialId']").val();
            var serialNo = $(this).parent().find("input[name='hidSerialNo']").val();
            var serialRemark = $(this).parent().find("input[name='hidSerialRemarks']").val();
            ChooseGoods(this, this.value, count, serialId, serialNo, serialRemark, productSn);
        }
    });
    if (flag == 1 && productSn == "1" && ((hidIsOpenIO == "1" && hidIsRealTimeIO == "1") || hidIsOpenIO == "0")) {
        SelectProductSingleSelectSerialNo(strProductIds, strRowIds, warehouseId, BusiAction);
    }
}
//商品数量修改
function updateGoodsNum(obj, pid, count, serialId, serialNo, serialremark) {
    var chooseGoods;
    var BusiAction = request("BusiAction");
    if (count == "") { count = 0; }
    chooseGoods = parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val();

    if (count > 0) {//选中
        $(obj).attr("checked", "checked");
        if (chooseGoods.indexOf(itemStr) < 0) {
            var goodsArr = new Array();
            goodsArr = chooseGoods.split(',');
            var n = -1;
            var temp = "";
            for (var i = 0; i < goodsArr.length; i++) {
                temp = goodsArr[i];
                if (temp.indexOf(pid) >= 0) {
                    n = i;
                    break;
                }
            }
            if (n >= 0) {
                goodsArr.remove(n);
            }
            var itemStr = pid + "|" + count + "|" + serialId + "|" + serialNo + "|" + serialremark;
            goodsArr.push(itemStr);
            parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val(goodsArr.join(','));
        }
    }
    else {//取消
        $(obj).removeAttr("checked");
        if (chooseGoods.indexOf(pid) >= 0) {
            var goodsArr = new Array();
            goodsArr = chooseGoods.split(',');
            var n = -1;
            var temp = "";
            for (var i = 0; i < goodsArr.length; i++) {
                temp = goodsArr[i];
                if (temp.indexOf(pid) >= 0) {
                    n = i;
                    break;
                }
            }
            if (n >= 0) {
                goodsArr.remove(n);
            }
            $(obj).parent().parent().children('td').eq(10).find("input[name='TxgoodsNum']").val("");
            parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val(goodsArr.join(','));
        }
    }
    SumGoodsNum();
}
function SumGoodsNum() {  
	var count = parent.$("#tabs .panel:visible iframe")[0].contentWindow.getSelProductCount();	
    $("#spanGoodsNum").text(count);
}

function UpdateBill2Pop(pid, count, serialId, serialNo, serialremark) {
    var chooseGoods;
    var BusiAction = request("BusiAction");
    if (count == "") { count = 0; }
    chooseGoods = parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val();
    if (obj.checked) {//选中
        if ($(obj).parent().find("input[name='hidSNManage']").val() == 1) {
            GetSerialNo($(obj).parent().parent().children("td").eq(10).find("input[name='TxgoodsNum']"), pid);
            return;
        }
        if (count == 0) {
            count = 1;
            $(obj).parent().parent().children('td').eq(10).find("input[name='TxgoodsNum']").val(count)
        }
        if (chooseGoods.indexOf(itemStr) < 0) {
            var itemStr = pid + "|" + count + "|" + serialId + "|" + serialNo + "|" + serialremark;
            chooseGoods = chooseGoods + "," + itemStr;
            parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val(chooseGoods);
        }
    }
    else {//取消
        if (chooseGoods.indexOf(pid + "|" + count) >= 0) {
            var goodsArr = new Array();
            goodsArr = chooseGoods.split(',');
            var n = -1;
            for (var i = 0; i < goodsArr.length; i++) {
                if (goodsArr[i] == (pid + "|" + count)) {
                    n = i;
                    break;
                }
            }
            if (n >= 0) {
                goodsArr.remove(n);
            }
            $(obj).parent().parent().children('td').eq(10).find("input[name='TxgoodsNum']").val("");
            $(obj).parent().find("input[name='hidSerialId']").val("");
            $(obj).parent().find("input[name='hidSerialNo']").val("");
            $(obj).parent().find("input[name='hidSerialRemarks']").val("");
            parent.$("#tabs .panel:visible iframe")[0].contentWindow.$("#hid" + BusiAction + "ChooseGoods").val(goodsArr.join(','));
        }
    }
}

function rowsClick(obj, pid, productSn) {
    var checkState = $(obj).parent().find("input[selable='1']").attr("checked");
    if (checkState == "checked") {
        $(obj).parent().find("input[selable='1']").removeAttr("checked");
    }
    else {
        $(obj).parent().find("input[selable='1']").attr("checked", "checked");
    }
    ChooseGoods($(obj).parent().find("input[selable='1']"),
        pid,
        $("#TxgoodsNum_" + pid).val(),
        $(obj).parent().find("input[name='hidSerialId']").val(),
        $(obj).parent().find("input[name='hidSerialNo']").val(),
        $(obj).parent().find("input[name='hidSerialRemarks']").val(),
        productSn);
}
function GetEmptyRow() {
    var rows = $("#tabProducts tr[id!='trTmp']");
    for (var i = 1; i < rows.length; i++) {
        if ($(rows[i]).children('td').eq(2).find("input:hidden[name='hidProductId']").val() == "") {
            if (i == rows.length) {
                addRow();
            }
            return rows[i];
        }
    }
    return addRow();
}